package service

import (
	"monitoring-api/models"
	"monitoring-api/pkg/jwt"
	"monitoring-api/serializer"
	"time"
)

// UserRegisterService 管理用户注册服务
type UserRegisterService struct {
	Name     string `from:"name" json:"name"`
	Email    string `form:"email" json:"email"`
	Password string `form:"password" json:"password" binding:"required,min=6,max=40"`
}

// valid 验证表单
func (service *UserRegisterService) valid() *serializer.Response {
	var count int64
	models.MySql.Model(&models.User{}).Where("email = ?", service.Email).Count(&count)
	if count > 0 {
		return &serializer.Response{
			Code:    40001,
			Message: "邮箱已被注册",
		}
	}
	return nil
}

func (service *UserRegisterService) Register() serializer.Response {
	user := models.User{
		Name:  service.Name,
		Email: service.Email,
	}
	// 表单验证
	if err := service.valid(); err != nil {
		return *err
	}

	// 加密密码
	if err := user.SetPassword(service.Password); err != nil {
		return serializer.Err(
			serializer.CodeEncryptError,
			"密码加密失败",
			err,
		)
	}
	// 生成用户id
	uuid := time.Now().Unix() + 20020809
	user.UserID = uuid
	// 创建用户
	if err := models.MySql.Create(&user).Error; err != nil {
		return serializer.ParamErr("注册失败", err)
	}
	// 生成token
	token, err := jwt.GenToken(user.UserID, user.Name)
	if err != nil {
		return serializer.ParamErr("注册失败", err)
	}
	return serializer.BuildUserResponse(user, token)
}
